<template>
    <div>
        <div class="btns">
            <el-button type="primary" icon="el-icon-download" @click="downloadTemplate">下载模板</el-button>
            <el-button type="success" icon="el-icon-upload2" @click="showImportDialog = true">批量导入</el-button>
            <el-button type="success" icon="el-icon-upload2" @click="exportTable">导出当前子表</el-button>
        </div>
        <avue-form v-on="$listeners" v-bind="$attrs" :option="formOption" v-model="formValue"></avue-form>
        <el-dialog 
            title="批量导入订单明细" 
            :visible.sync="showImportDialog" 
            width="800px"
            :close-on-click-modal="false">
            <div class="import-steps">
                <div class="step" :class="{active: importStep === 1}">
                    <div class="step-icon">1</div>
                    <div class="step-title">上传文件</div>
                </div>
                <div class="step" :class="{active: importStep === 2}">
                    <div class="step-icon">2</div>
                    <div class="step-title">数据预览</div>
                </div>
                <div class="step" :class="{active: importStep === 3}">
                    <div class="step-icon">3</div>
                    <div class="step-title">完成导入</div>
                </div>
                <div class="step-line"></div>
                </div>

                <div v-if="importStep === 1">
                    <div class="file-upload-area" @click="$refs.fileInput.click()">
                        <div class="file-upload-icon">
                            <i class="el-icon-upload"></i>
                        </div>
                        <p class="file-upload-text">点击或将文件拖拽到此处上传</p>
                        <p class="file-upload-text">支持 <strong>.xlsx</strong> 或 <strong>.xls</strong> 格式文件</p>
                        <input 
                            type="file" 
                            ref="fileInput" 
                            style="display:none" 
                            accept=".xlsx, .xls"
                            @change="handleFileUpload">
                    </div>
                </div>

                <div v-if="importStep === 2">
                    <div class="preview-table">
                        <el-table :data="previewData" border height="300">
                            <el-table-column v-for="(item, index) in tableTitle" :key="index" :label="item.label" :prop="item.prop"></el-table-column>
                            <!-- <el-table-column label="状态" width="100" align="center">
                                <template slot-scope="scope">
                                    <el-tag v-if="isRowValid(scope.row)" type="success" size="small">有效</el-tag>
                                    <el-tag v-else type="danger" size="small">无效</el-tag>
                                </template>
                            </el-table-column> -->
                        </el-table>
                    </div>
                    
                    <div class="operation-buttons">
                        <el-button @click="importStep = 1">上一步</el-button>
                        <el-button type="primary" @click="confirmImport">确认导入</el-button>
                    </div>
                </div>

                <div v-if="importStep === 3">
                <el-result
                    icon="success"
                    title="导入成功"
                    :subTitle="`成功导入 ${previewData.length} 条明细数据`">
                </el-result>
                
                <div class="operation-buttons">
                    <el-button @click="closeImportDialog">关闭</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import * as XLSX from 'xlsx';
export default {
    props: {
        value: {
            type: Object,
            default: () => {
                return {};
            },
        },
        option: {
            type: Object,
            default: () => {
                return {};
            },
        },
    },
    data() {
        return {
            formValue: this.value || {},
            formOption: this.option || {},
            showImportDialog: false,
            importStep: 1,
            previewData: [],
            tableTitle: [],
        };
    },
    methods: {
        addAll() {
            for (let i = 0; i < 10; i++) {
                this.formValue.dynamic.push({
                    input: 1,
                    select: 1,
                });
            }
        },
        // 下载模板
        downloadTemplate() {
            // 创建模板数据
            const templateData = [
                ['输入框', '选择框', ],
                ['2', '2', ],
                ['3', '3', ],
                ['4', '4', ]
            ];
            
            // 创建工作簿
            const ws = XLSX.utils.aoa_to_sheet(templateData);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "订单明细模板");
            
            // 生成文件并下载
            XLSX.writeFile(wb, "订单明细模板.xlsx");
            
            this.$message({
                message: '模板下载成功',
                type: 'success'
            });
        },
        // 处理文件上传
        handleFileUpload(e) {
            const file = e.target.files[0];
            if (!file) return;
            
            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });
                    const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                    const jsonData = XLSX.utils.sheet_to_json(firstSheet);
                    
                    if (jsonData.length === 0) {
                        this.$message.error('文件无数据');
                        return;
                    }
                    // 转换为明细格式
                    this.tableTitle = this.formOption.column.find(col => col.prop === 'dynamic').children.column.map(col => { return{label:col.label,prop:col.prop} });
                    this.previewData = jsonData.map(row => {
                        let tableRow = {};
                        const keys = Object.keys(row);
                        this.tableTitle.map(col => {
                            if(keys.includes(col.label)){
                                tableRow[col.prop] = row[col.label];
                            }
                        })
                        return tableRow;
                    })
                    this.importStep = 2;
                } catch (error) {
                    this.$message.error('文件解析失败: ' + error.message);
                }
            };
            reader.readAsArrayBuffer(file);
        },
        
        // 检查行数据是否有效
        isRowValid(row) {
            return row.productName && row.quantity > 0 && row.price >= 0;
        },
        
        // 确认导入
        confirmImport() {
            // 过滤无效数据
            // const validData = this.previewData.filter(this.isRowValid);
            const validData = this.previewData
            
            if (validData.length === 0) {
                this.$message.error('没有有效数据可导入');
                return;
            }
            
            // 添加到明细列表
            validData.forEach(item => {
                this.formValue.dynamic.push(item);
            })
            
            this.$message({
                message: `成功导入 ${validData.length} 条明细数据`,
                type: 'success'
            });
            
            this.importStep = 3;
        },
        
        // 关闭导入对话框
        closeImportDialog() {
            this.showImportDialog = false;
            this.importStep = 1;
            this.previewData = [];
        },
        exportTable() {
            // 创建模板数据
            const tableColumn = this.formOption.column.find(col => col.prop === 'dynamic').children.column.map(col => { return{label:col.label,prop:col.prop} });
            const tableTitle = tableColumn.map(col => col.label);
            const tableData = this.formValue.dynamic.map(item => {
                const keys = Object.keys(item)
                let arr = []
                tableColumn.map(child => {
                    if(keys.includes(child.prop)){
                        arr.push(item[child.prop])
                    }
                })
                return arr
            })
            tableData.unshift(tableTitle);
            // 创建工作簿
            const ws = XLSX.utils.aoa_to_sheet(tableData);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "子表单1");
            // 生成文件并下载
            XLSX.writeFile(wb, "子表单.xlsx");
        }
    },
};
</script>
<style>
    .btns{
        text-align: right;
        margin-bottom: 10px;
    }
    .operation-buttons {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        margin-top: 15px;
    }
    .import-steps {
        display: flex;
        justify-content: space-between;
        margin: 20px 0;
        position: relative;
    }
    .step {
        text-align: center;
        flex: 1;
        position: relative;
        z-index: 1;
    }
    .step-icon {
        width: 36px;
        height: 36px;
        line-height: 36px;
        border-radius: 50%;
        background: #e4e7ed;
        color: #fff;
        display: inline-block;
        font-weight: bold;
        margin-bottom: 10px;
    }
    .step.active .step-icon {
        background: #409EFF;
    }
    .step-title {
        font-weight: bold;
        color: #606266;
    }
    .step.active .step-title {
        color: #409EFF;
    }
    .step-line {
        position: absolute;
        top: 18px;
        left: 0;
        right: 0;
        height: 2px;
        background: #e4e7ed;
        z-index: 0;
    }
    .file-upload-area {
        border: 2px dashed #dcdfe6;
        border-radius: 6px;
        padding: 40px 20px;
        text-align: center;
        cursor: pointer;
        transition: border-color 0.3s;
        background: #fafafa;
    }
    .file-upload-area:hover {
        border-color: #409EFF;
    }
    .file-upload-icon {
        font-size: 48px;
        color: #c0c4cc;
        margin-bottom: 20px;
    }
    .file-upload-text {
        color: #606266;
        font-size: 14px;
    }
    .file-upload-text strong {
        color: #409EFF;
    }
</style>